package com.campus_assistant.service.elasticsearch;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import com.alibaba.fastjson.JSON;
import com.campus_assistant.config.db.DynamicDataSource;
import com.campus_assistant.mapper.db1.CoursesMapper;
import com.campus_assistant.mapper.db1.ScoresMapper;
import com.campus_assistant.mapper.db1.StudentMapper;
import com.campus_assistant.pojo.db1.Courses;
import com.campus_assistant.pojo.db1.Scores;
import com.campus_assistant.pojo.db1.Student;
import com.campus_assistant.pojo.vo.StudentES;
import com.campus_assistant.pojo.vo.StudentScores;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchPhraseQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class ElasticSearchService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;


    public Boolean initStudent(List<Student> stu_infoListAll) throws IOException {

        BulkRequest bulkRequest=new BulkRequest();//插入数据
        bulkRequest.timeout("2m");//超时时间
        Student student =null;
        for (int i=0;i<stu_infoListAll.size();i++){
            student=stu_infoListAll.get(i);
            bulkRequest.add(new IndexRequest("student")
                    .source(JSON.toJSONString(student), XContentType.JSON));
        }
        BulkResponse bulk=restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);//执行数据插入
        return !bulk.hasFailures();
    }

    public Boolean initCourses(List<Courses> courses) throws IOException {
        BulkRequest bulkRequest=new BulkRequest();//插入数据
        bulkRequest.timeout("2m");//超时时间
        for (int i=0;i<courses.size();i++){
            bulkRequest.add(new IndexRequest("courses")
                    .source(JSON.toJSONString(courses.get(i)), XContentType.JSON));
        }
        BulkResponse bulk=restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);//执行数据插入
        return !bulk.hasFailures();
    }

    public Boolean initScores(List<StudentScores> scores) throws IOException {
        BulkRequest bulkRequest=new BulkRequest();//插入数据
        bulkRequest.timeout("2m");//超时时间
        for (int i=0;i<scores.size();i++){
            bulkRequest.add(new IndexRequest("scores")
                    .source(JSON.toJSONString(scores.get(i)), XContentType.JSON));
        }
        BulkResponse bulk=restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);//执行数据插入
        return !bulk.hasFailures();
    }

    public List<StudentES> searchStudentByNameES(String keyword){
        //进行条件搜索
        SearchRequest searchRequest=new SearchRequest("student");
        SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();
        //开始精确匹配
        MatchPhraseQueryBuilder term= QueryBuilders.matchPhraseQuery("sName",keyword);
        sourceBuilder.query(term);//开始查询
        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //进行高亮设置
        HighlightBuilder highlightBuilder=new HighlightBuilder();
        highlightBuilder.field("sName");
        highlightBuilder.preTags("<tspan style='fill:red'>");
        highlightBuilder.postTags("</tspan>");
        sourceBuilder.highlighter(highlightBuilder);

        searchRequest.source(sourceBuilder);//执行搜索
        SearchResponse searchResponse=null;
        try {
            searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ArrayList<StudentES> res = new ArrayList<>();//存放返回的结果1
        ArrayList<Map<String,Object>> list = new ArrayList<>();//存放ES查询出来的结果
        String studentName=null;
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();//获取高亮字段
            HighlightField sName = highlightFields.get("sName");//获取学生姓名
            Map<String,Object> stringObjectMap=hit.getSourceAsMap();
            if (sName!=null){//存在高亮字段
                Text[] fragments = sName.fragments();//取出高亮字段
                String name="";
                for (Text fragment : fragments) {
                    name+=fragment;
                }
                stringObjectMap.put("sName",name);//替换高亮字段
            }

            list.add(hit.getSourceAsMap());

        }
        for (Map<String, Object> map : list) {
            ArrayList<Map<String,Object>> newList=new ArrayList<>();
            newList.add(getDataByName((String) map.get("sNum"),list));
            res.add(new StudentES((String) map.get("sName"),newList));
            System.out.println((String) map.get("sName"));
            System.out.println(newList);
        }
        System.out.println("结果为：");
        System.out.println(res);
        return res;
    }
    Map<String,Object> getDataByName(String sNum,ArrayList<Map<String,Object>> lists){
        for (Map<String, Object> list : lists) {
            String sNum2 = (String)list.get("sNum");
            if (sNum2.equals(sNum)){
                return list;
            }
        }
        return null;
    }

}
